/*
 * #!
 * Ontopia Engine
 * #-
 * Copyright (C) 2001 - 2013 The Ontopia Project
 * #-
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * !#
 */

package net.ontopia.topicmaps.query.impl.basic;

import java.util.Iterator;

import net.ontopia.infoset.core.LocatorIF;
import net.ontopia.topicmaps.core.TopicIF;

/**
 * INTERNAL: Common code-sharing superclass for dynamic predicates.
 */
public abstract class AbstractDynamicPredicate implements BasicPredicateIF {
  protected String name;
  protected TopicIF type;
  protected LocatorIF base;

  public AbstractDynamicPredicate(String name) {
    // used for DynamicFailurePredicates generated by optimizer
    this.name = name;
  }

  public AbstractDynamicPredicate(TopicIF type, LocatorIF base) {
    this.type = type;
    this.base = base;
  }

  @Override
  public String getName() {
    if (name != null)
      return name;
    
    if (base == null)
      return "@" + type.getObjectId();
    
    Iterator it = type.getItemIdentifiers().iterator();
    String baseadr = base.getAddress();
    while (it.hasNext()) {
      LocatorIF loc = (LocatorIF) it.next();
      String address = loc.getAddress();
      if (address.startsWith(baseadr))
        return address.substring(baseadr.length() + 1);
    }
    return "@" + type.getObjectId();
  }

  public TopicIF getType() {
    return type;
  }
}
